import { createStore, applyMiddleware } from 'redux'

// 导入 saga
import createSagaMiddleware from 'redux-saga'
// 导入根 reducer
import rootReducer from './reducers'
import sagas from './sagas'

// 创建 saga 中间件
const sagaMiddleware = createSagaMiddleware()

let middlewares

// 根据环境决定是否需要使用 redux-devtools-extension
if (process.env.NODE_ENV === 'development') {
  const { composeWithDevTools } = require('redux-devtools-extension')
  const composeEnhancers = composeWithDevTools({})
  middlewares = composeEnhancers(applyMiddleware(...[sagaMiddleware]))
} else if (process.env.NODE_ENV === 'production') {
  middlewares = applyMiddleware(sagaMiddleware)
}

// 初始化已有的state
const preloadedState = {
  login: {
    token: localStorage.getItem('erabbit_token') || '',
    userInfo: JSON.parse(localStorage.getItem('erabbit_userInfo')!) || {}
  }
}

const store = createStore(rootReducer, preloadedState, middlewares)

sagaMiddleware.run(sagas)

export type RootState = ReturnType<typeof store.getState>

export default store
